package gemini.castor.ui.client.page.content.store.searchproduct.searchproductform;

import gemini.basic.dto.SearchProductCriteria;
import gemini.basic.model.Product;
import gemini.basic.model.ProductType;
import gemini.castor.ui.client.ServiceCatalog;
import gemini.castor.ui.client.mvp.callback.AbstractAsyncCallback;
import gemini.castor.ui.client.mvp.single.CastorWidgetDisplay;
import gemini.castor.ui.client.mvp.single.CastorWidgetPresenter;
import gemini.castor.ui.client.page.RootEvent;
import gemini.castor.ui.client.utils.GuiUtils;
import gemini.castor.ui.client.utils.PlaceConstants;

import java.util.ArrayList;
import java.util.List;

import ch.elca.gwt.mvp.client.EventBus;
import ch.elca.gwt.mvp.client.place.Place;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.inject.Inject;

public class SearchProductFormPresenter extends
		CastorWidgetPresenter<SearchProductFormPresenter.Display> {

	@Inject
	public SearchProductFormPresenter(Display display, EventBus globalEventBus) {
		super(display, globalEventBus);
	}

	public interface Display extends CastorWidgetDisplay {
		boolean isValidate();
		HasClickHandlers getSearchClickHandlers();
		SearchProductCriteria getSearchCriteria();
		void setProductTypes(List<ProductType> productTypes);
		void showResult(ArrayList<Product> result);
	}

	public static final Place PLACE = new Place(PlaceConstants.PLACE_SEARCH_PRODUCT);

	@Override
	protected void onBind() {
		registerHandler(display.getSearchClickHandlers().addClickHandler(
				new ClickHandler() {
					public void onClick(ClickEvent event) {
						if(display.isValidate()){
							searchProduct();
						}
					}
				}));
		
		eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.MASK));
		ServiceCatalog.getSearchProductService().getAllCategory(
				new AbstractAsyncCallback<ArrayList<ProductType>>() {

					@Override
					public void onSuccess(ArrayList<ProductType> result) {
						eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.UN_MASK));
						if (result != null) {
							display.setProductTypes(result);
							display.loadData();
						} else {
							GuiUtils.alert("Cannot find any product type in db");
						}
					}
				});
	}
	
	protected void searchProduct() {
		SearchProductCriteria criteria = display.getSearchCriteria();
		
		eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.MASK));
		ServiceCatalog.getSearchProductService().findProduct(criteria,
				new AbstractAsyncCallback<ArrayList<Product>>() {

					@Override
					public void onSuccess(
							ArrayList<Product> result) {
						eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.UN_MASK));
						display.showResult(result);
					}
				});
	}

	@Override
	public Place getPlace() {
		return PLACE;
	}
}
